// pages/confirmOrder/confirmOrder.js
import { goodsDateils, addressList, getUserCouponList, orderSign, orderAdd, orderPaySign, orderPay } from '../../api/url.js'
import { formatAddrCodeToString, formatTime, formatOrderPayTime, getRandomNum } from '../../utils/util.js'
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    totalPriTxt: '',//商品总价显示价格
    finalPriTxt: '',//最终显示价格
    fromCart: false,//是否从购物车跳转
    listInfo: [],//商品数据
    list: [],//商品列表
    totalPrice: 0,//商品总价
    showAddr: null,//显示地址
    message: '',//给商家留言
    coupons: [],//可用优惠券列
    selectedCoupon: null,//选择的优惠券
    isIPX:false,//是否是iphoneX
  },
  /**
   * @method
   * @desc 计算显示价格
   */
  calFinalPriTxt() {
    let that = this
    if (that.data.selectedCoupon) {
      if (that.data.selectedCoupon.vouchers.fTypeName==='代金券'){
        let temTotal = that.data.totalPrice - that.data.selectedCoupon.vouchers.fMoney
        that.setData({
          finalPriTxt: temTotal.toFixed(2)
        })
      } else if (that.data.selectedCoupon.vouchers.fTypeName === '折扣券'){
        let temTotal = that.data.totalPrice * that.data.selectedCoupon.vouchers.fMoney
        that.setData({
          finalPriTxt: temTotal.toFixed(2)
        })
      }else {
        wx.showToast({
          title: '未知优惠券',
          icon:'none'
        })
      }
    } else {
      that.setData({
        finalPriTxt: that.data.totalPrice.toFixed(2)
      })
    }
  },
  /**
   * 支付订单
   */
  payOrder(orderId, orderNo, toPay, desc, createTime, jsCode) {
    const time = formatOrderPayTime(Date.now())
    const random = getRandomNum(6)
    const amount = toPay.toFixed(2)
    wx.request({
      url: orderPaySign,
      data:{
        time,
        randomKey: random,
        orderNo: orderId,
        loginName: app.globalData.userInfo.loginname,
        token: wx.getStorageSync('token'),
        userId: app.globalData.userInfo.id,
        fUserId: app.globalData.userInfo.id
      },
      header:{
        'content-type': 'application/x-www-form-urlencoded'
      },
      method:'POST',
      success(res){
        if(res.data.code===0){//获取支付签名成功
          const digest = res.data.msg
          var userId = app.globalData.userInfo.id
          var loginName = app.globalData.userInfo.loginname
          wx.request({
            url: orderPay,
            method:'POST',
            header: {
              'content-type': 'application/json',
              userId,
              Time: time,
              Authentication: `${loginName}:${random}:${amount}:${digest}`,
            },
            data:{
              orderID: orderId,
              orderCode: orderNo,
              payCode: orderNo,
              description: JSON.stringify('购买' + desc),
              appId: 'wxf34e48c761b604a2',
              appSecret: 'debe1169aaa6545cf433aaad69c107da',
              jsCode: jsCode,
              onLineStyle: 'wechat',
              browseType: 'app',
              toPay: amount,
              sellerCode: '2088801555885173',
              sellerName: JSON.stringify(desc),
              requestBiz: '001',
              createTime: Date.now(),
              invalidTime: 6000,
              loginName: app.globalData.userInfo.loginname,
              token: wx.getStorageSync('token'),
              userId: app.globalData.userInfo.id,
              fUserId: app.globalData.userInfo.id
            },
            success(res){
              console.log(res)
              if (res.data.errorCode==='0'){
                //得到支付参数付款
                console.log('打印支付参数')
                console.log(res)
                const data = JSON.parse(res.data.data.payData)
                console.log(data)
                wx.requestPayment({
                  'timeStamp': data.timeStamp,
                  'nonceStr': data.nonceStr,
                  'package': data.package,
                  'signType': 'MD5',
                  'paySign': data.sign,
                  'success': function (res) {
                    if (res.errMsg === 'requestPayment:ok') {
                      wx.hideLoading()
                      wx.showToast({
                        title: '支付成功',
                        icon: 'none'
                      })
                      setTimeout(function () {
                        wx.switchTab({
                          url: '/pages/order/order',
                        })
                      }, 1000)
                    } else {
                      wx.showToast({
                        title: '支付失败',
                        icon: 'none'
                      })
                      setTimeout(function () {
                        wx.switchTab({
                          url: '/pages/order/order?type=1',
                        })
                      }, 1000)
                    }
                  },
                  'fail': function (err) {
                    wx.hideLoading()
                    wx.showToast({
                      icon: 'none',
                      title: err.msg || '订单支付失败',
                    })
                    setTimeout(function () {
                      wx.switchTab({
                        url: '/pages/order/order?type=1',
                      })
                    }, 1000)
                  }
                })
              }else{
                wx.showToast({
                  title: '获取支付参数异常',
                })
              }
            },
            fail(){
              wx.showToast({
                title: '获取支付参数失败',
              })
            }
          })
        }else{
          wx.showToast({
            title: '获取支付签名异常',
          })
        }
      },
      fail(){
        wx.showToast({
          title: '获取支付签名失败',
          icon:'none'
        })
      }
    })
  },
  /**
   * 提交订单
   */
  tapSubmitOrder: function () {
    let that = this
    const {
      showAddr,
      totalPrice,
      message,
      invoice
    } = this.data
    const sku = that.data.listInfo.map(i => `${i.goodsId}:${i.count}:${i.skuId}`).join(';')
    const fOrderAmount = totalPrice
    const fReallyAmount = totalPrice
    const fAddressId = showAddr.fId
    const fRemark = message
    const req = that.data.fromCart ? 1 : 0 //是否是购物车跳转
    wx.showLoading({
      title: '支付中',
      mask: true
    })
    wx.request({
      url: orderSign,
      data: {
        _suc_sku: sku,
        fOrderAmount,
        fReallyAmount,
        loginName: app.globalData.userInfo.loginname,
        token: wx.getStorageSync('token'),
        userId: app.globalData.userInfo.id,
        fUserId: app.globalData.userInfo.id
      },
      success(res){
        if(res.data.code===0){//获取签名成功
          wx.request({
            url: orderAdd,
            data:{
              fSucSku: sku,
              fOrderAmount,
              fReallyAmount,
              timestamp: Date.parse(new Date()),
              sign: res.data.response.cont,
              fAddressId,
              fRemark,
              shopInfo: '',
              req,
              fInvoiceId: invoice ? invoice.id : '',
              vouchersId: that.data.selectedCoupon ? that.data.selectedCoupon.fId : '',
              loginName: app.globalData.userInfo.loginname,
              token: wx.getStorageSync('token'),
              userId: app.globalData.userInfo.id,
              fUserId: app.globalData.userInfo.id
            },
            success(res){
              if(res.data.code===0){//添加订单成功
                const order = res.data.response.cont
                let desc = ''
                if (order.list && order.list.length>0) {
                  desc += order.list.map(i => `${i.fProductName}x${i.fCount}`).join(';')
                }
                wx.login({
                  success: res => {
                    // 发送 res.code 到后台换取 openId, sessionKey, unionId
                    that.payOrder(order.fId, order.fOrderId, order.fOrderAmount, desc, order.fCreatedatatime, res.code)
                  },
                  fail: res => {
                    wx.showToast({
                      icon: 'none',
                      title: '微信认证失败',
                    })
                  }
                })
              }else{
                wx.showToast({
                  title: '添加订单异常',
                  icon:'none'
                })
                setTimeout(function(){
                  wx.switchTab({
                    url: '/pages/shopCart/shopCart',
                  })
                },1000)
              }
            },
            fail(){
              wx.showToast({
                title: '添加订单失败',
                icon:'none'
              })
            }
          })
        }else{
          wx.showToast({
            title: '获取签名异常',
            icon:'none'
          })
        }
      },
      fail(){
        wx.showToast({
          title: '获取签名失败',
          icon:'none'
        })
      }
    })
  },
  /**
   * @method
   * @desc 跳转优惠券页
   */
  goCoupons() {
    let that = this
    if (that.data.coupons && that.data.coupons.length > 0) {
      wx.navigateTo({
        url: '/pages/coupons/coupons?fromPage=confirmOrder&totalPri=' + that.data.totalPrice,
      })
    }
  },
  /**
   * @method
   * @desc 加载优惠券
   */
  loadCoupons() {
    let that = this
    wx.request({
      url: getUserCouponList,
      data: {
        page: 1,
        size: 9999,
        loginName: app.globalData.userInfo.loginname,
        token: wx.getStorageSync('token'),
        userId: app.globalData.userInfo.id,
        fUserId: app.globalData.userInfo.id
      },
      success(res) {
        if (res.data.code === 0) {
          let temList = res.data.response.cont.list
          temList = temList.filter(val => val.vouchers)
          temList = temList.filter(val => val.vouchers.fMinMoney <= that.data.totalPrice)
          temList.forEach(val => {
            val.beginTime = formatTime(val.vouchers.fBegin).split(' ')[0]
            val.endTime = formatTime(val.vouchers.fEnd).split(' ')[0]
          })
          that.setData({
            coupons: temList
          })
        } else {
          wx.showToast({
            title: '获取优惠券异常',
            icon: 'none'
          })
        }
      }
    })
  },
  /**
   * @method
   * @desc 设置留言
   */
  setMessage(e) {
    let that = this
    that.setData({
      message: e.detail.value
    })
  },
  /**
   * 加载商品
   */
  loadGoodsList(listInfo) {
    let that = this
    that.data.listInfo.map(i => {
      wx.request({
        url: goodsDateils,
        data: {
          id: i.goodsId
        },
        success(res) {
          if (res.data.code === 0) {
            that.loadCoupons()
            let temData = that.data.list//原先的列表
            let temToatalPri = that.data.totalPrice//总价格
            let temDetail = res.data.response.cont//商品详情
            temDetail.thumbImg = app.globalData.imageBaseUrl + temDetail.productImgList[0].fThumbImage
            let temPri//有sku为sku价格  没为商品价格
            if (temDetail.skuAndPropAndPropValList && temDetail.skuAndPropAndPropValList.length > 0) {
              let temSku = temDetail.skuAndPropAndPropValList.filter(val => (val.fId + '') === i.skuId)[0]
              temPri = temSku.fPrice
              temDetail.skuTxt = temSku.skuPropIdAndNameAndValIdAndNameList.map(val1 => {
                return val1.fPropName + ':' + val1.fPropValName
              }).join(';')
            } else {
              temPri = temDetail.fFixedPrice
              temDetail.skuTxt = '默认规格'
            }
            temDetail.priceTxt = temPri.toFixed(2)//显示价格
            temDetail.count = Number(i.count)//数量
            temData.push(temDetail)
            temToatalPri += temPri * Number(i.count)
            that.setData({
              list: temData,
              totalPrice: temToatalPri,
              totalPriTxt: temToatalPri.toFixed(2)
            })
            that.calFinalPriTxt()
          } else {
            wx.showToast({
              title: res.data.msg || '商品加载异常',
            })
          }
        },
        fail() {
          wx.showToast({
            title: '商品加载失败',
            icon: 'none'
          })
        }
      })
    })
  },
  //选择地址
  tapSelectAddress() {
    wx.navigateTo({
      url: '../addressList/addressList?fromPage=confirmOrder'
    })
  },
  //点击图片跳转到订单详情
  goGoodsDetail: function () {
    wx: wx.navigateTo({
      url: '../goodsDetail/goodsDetail',
    })
  },
  /**
   * 加载地址
   */
  loadAddress() {
    let that = this
    wx.request({
      url: addressList,
      data: {
        loginName: app.globalData.userInfo.loginname,
        token: wx.getStorageSync('token')
      },
      success(res) {
        if (res.data.code === 0) {
          const addresses = res.data.response.cont || []
          if (addresses && addresses.length > 0) {
            let addr = addresses.find(i => i.fIsDefault == 0) || addresses[0]
            addr.addrTxt = formatAddrCodeToString(addr.fProvinceNum, addr.fCityNum, addr.fAreaNum) + '-' + addr.fDetailInfo || ''
            that.setData({
              showAddr: addr
            })
          } else {
            wx.showModal({
              title: 'Tips',
              content: '您还没有添加地址哦~',
              confirmText: '现在添加',
              success(res) {
                if (res.confirm) {
                  wx.navigateTo({
                    url: '/pages/addressEdit/addressEdit',
                  })
                }
              }
            })
          }
        }
      }
    })
  },
  //选择地址
  tapSelectAddress() {
    wx.navigateTo({
      url: '../addressList/addressList?select=1'
    })
  },
  //点击图片跳转到订单详情
  goGoodsDetail: function () {
    wx: wx.navigateTo({
      url: '../goodsDetail/goodsDetail',
    })
    that.loadGoodsList(that.data.listInfo)
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this
    const goodsData = options.data.split(';')
    const listInfo = goodsData.map(i => {
      const data = i.split(':')
      return {
        goodsId: data[0],
        skuId: data[1],
        count: data[2]
      }
    })
    that.setData({
      fromCart: !!options.fromCart,
      listInfo: listInfo,
      isIPX:app.globalData.isIPX
    })
    that.loadGoodsList()
    that.loadAddress()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    let that=this
    that.setData({

    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})